package cn.pengyinrui.pethome.base.controller;


import cn.pengyinrui.pethome.base.query.BaseQuery;
import cn.pengyinrui.pethome.base.service.IBaseService;
import cn.pengyinrui.pethome.dept.domain.Department;
import cn.pengyinrui.pethome.dept.query.DepartmentQuery;
import cn.pengyinrui.pethome.utils.AjaxResult;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

public class BaseController<T> {
    @Autowired
    private IBaseService<T> service;

    @GetMapping("/list")
    @ApiOperation(value = "查询全部数据")
    public AjaxResult findAll(){
        try {
            return AjaxResult.success()
                    .setData(service.findAll())
                    .setTotal(service.findAllByQueryCount(new BaseQuery()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @PostMapping("/{id}")
    @ApiOperation(value = "根据id查询信息")
    public AjaxResult findOne(@PathVariable("id") Long id){
        try {
            return AjaxResult.success()
                    .setData(service.findOne(id))
                    .setTotal(service.findAllByQueryCount(new BaseQuery()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @PostMapping("/query")
    @ApiOperation(value = "分页查询")
    public AjaxResult findAllByQuery(@RequestBody BaseQuery query){
        try {
            return AjaxResult.success()
                    .setData(service.findAllByQuery(query))
                    .setTotal(service.findAllByQueryCount(query));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.error();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除数据")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            service.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error().setTip(e.getMessage());
        }
    }

    @PostMapping
    @ApiOperation(value = "新增数据")
    public AjaxResult add(@RequestBody T t){
        try {
            service.add(t);
        } catch (Exception e) {
            return AjaxResult.error().setTip(e.getMessage());
        }
        return AjaxResult.success();
    }

    @PutMapping
    @ApiOperation(value = "修改数据")
    public AjaxResult update(@RequestBody T t){
        try {
            service.update(t);
        } catch (Exception e) {
            return AjaxResult.error().setTip(e.getMessage());
        }
        return AjaxResult.success();
    }
}
